
#include "widget_funcd_weather.h"
#include "ui_widget_funcd_weather.h"

Widget_funcD_Weather::Widget_funcD_Weather(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget_funcD_Weather)
{
    ui->setupUi(this);
    // 创建网络服务管理对象
    this->network_manager = new QNetworkAccessManager();
    // 初始化组件
    this->init_module();
    // 服务器收到数据后，与自定义槽函数相连
    connect(this->network_manager,&QNetworkAccessManager::finished,this,&Widget_funcD_Weather::onReplied);
    // 将城市文件内容放入容器中
    this->set_cityList();
    // 默认显示北京天气
    this->city_url = QUrl("http://t.weather.itboy.net/api/weather/city/101010100");
    this->get_joson();
    this->anlalysis_joson();
    this->show_json();
}

Widget_funcD_Weather::~Widget_funcD_Weather()
{
    delete ui;
}

// 将文件中的数据放入容器中
void Widget_funcD_Weather::set_cityList()
{
    QFile file("D:\\develop\\QT\\Qt_project\\Qt_Echo_Vision\\city.txt");
    file.open(QFile::ReadOnly);
    if (!file.isOpen())
    {
        QMessageBox::warning(this,"提示","city.txt不存在或已经被删除!", QMessageBox::Ok);
    }

    QTextStream in(&file);
    QString word;
    in.setCodec("UTF-8");  // 设置编码
    while(!in.atEnd())
    {
        in >> word;
        if (!word.isEmpty())
        {
             this->city_list.append(word);
        }
    }
    file.close();
}

// 用于设置图标
bool Widget_funcD_Weather::set_label_picture(QString name, QLabel &label)
{
    QPixmap label_dir = ":/" + name;

    if (label_dir.isNull())
    {
        QMessageBox::warning(this,"提示","图片路径不存在", QMessageBox::Ok);
        return false;
    }
    label.setPixmap(label_dir);
    return true;
}

// 用于设置文字
void Widget_funcD_Weather::set_label_text(QString name, QLabel &label)
{
    label.setText(name);
}

// 搜索城市，返回城市编号
QString Widget_funcD_Weather::find_city(QString city_name)
{
    int i = 0;
    while(i != this->city_list.size() - 1)
    {
        if (city_name == city_list.at(i))
        {
            return city_list.at(i - 1);
        }
        i++;
    }
    QMessageBox::warning(this,"提示","你搜索的城市有误!", QMessageBox::Ok);
    return NULL;
}

// 初始化组件
void Widget_funcD_Weather::init_module()
{
    // 设置搜索按键
    this->ui->pushButton->setIcon(QIcon(":/天气搜索"));
    ui->pushButton->setFlat(true);
    // 设置输入框
    ui->lineEdit->setStyleSheet("QLineEdit {"
                                "    border-radius: 8px;"
                                "    background-color: rgb(255,255,255);"
                                "}"
                               );
    // 设置城市显示框
    ui->textEdit->setStyleSheet("QTextEdit {"
                                "    border-radius: 8px;"
                                "    background-color: rgb(204, 235, 255);"
                                "    font-weight: bold;"
                                "}");
    // 设置 textEdit 样式的地方添加
    QFont font = ui->textEdit->font();
    font.setLetterSpacing(QFont::AbsoluteSpacing, 4); // 绝对字距 4 像素
    ui->textEdit->setFont(font);

    // 设置当天天气显示框架1
    ui->frame->setStyleSheet("QFrame {"
                                "    border-radius: 8px;"
                                "    background-color: rgb(255,255,255);"
                                "}"
                               );
    // 设置当天天气显示框架2
     ui->frame_2->setStyleSheet("QFrame {"
                                "    border-radius: 8px;"
                                "    background-color: rgb(255,255,255);"
                                "}"
                               );
    // 设置当天天气显示框架3
    ui->frame_3->setStyleSheet("QFrame {"
                                "    border-radius: 8px;"
                                "    background-color: rgb(255,255,255);"
                                "}"
                               );
    // 设置当天天气显示框架4
    ui->frame_4->setStyleSheet("QFrame {"
                                "    border-radius: 8px;"
                                "    background-color: rgb(255,255,255);"
                                "}"
                               );
    // 设置当天天气显示框架5
    ui->frame_5->setStyleSheet("QFrame {"
                                "    border-radius: 8px;"
                                "    background-color: rgb(255,255,255);"
                                "}"
                               );
    // 设置7天天气显示框架6
    ui->frame_6->setStyleSheet("QFrame {"
                                "    border-radius: 8px;"
                                "    background-color: rgb(255,255,255);"
                                "}"
                               );
    // 设置7天天气显示框架6
    ui->frame_7->setStyleSheet("QFrame {"
                                "    border-radius: 8px;"
                                "    background-color: rgb(255,255,255);"
                                "}"
                               );
    // 设置7天天气显示框架6
    ui->frame_8->setStyleSheet("QFrame {"
                                "    border-radius: 8px;"
                                "    background-color: rgb(255,255,255);"
                                "}"
                               );
    // 设置7天天气显示框架6
    ui->frame_9->setStyleSheet("QFrame {"
                                "    border-radius: 8px;"
                                "    background-color: rgb(255,255,255);"
                                "}"
                               );
    // 设置7天天气显示框架6
    ui->frame_10->setStyleSheet("QFrame {"
                                "    border-radius: 8px;"
                                "    background-color: rgb(255,255,255);"
                                "}"
                               );
    // 设置7天天气显示框架6
    ui->frame_11->setStyleSheet("QFrame {"
                                "    border-radius: 8px;"
                                "    background-color: rgb(255,255,255);"
                                "}"
                               );
    // 设置7天天气显示框架6
    ui->frame_12->setStyleSheet("QFrame {"
                                "    border-radius: 8px;"
                                "    background-color: rgb(255,255,255);"
                                "}"
                               );
}

// 发送对应城市HTTP请求
void Widget_funcD_Weather::get_joson()
{
    this->network_manager->get(QNetworkRequest(this->city_url));
}

// 设置URL
void Widget_funcD_Weather::set_url(QUrl url)
{
    this->city_url = url;
}

// 解析提取到JSON数据
void Widget_funcD_Weather::anlalysis_joson()
{
    QFile file("./weather.json");
    file.open(QFile::ReadOnly);
    QByteArray json_byte = file.readAll();
    file.close();

    QJsonDocument json_doc = QJsonDocument::fromJson(json_byte);
    if (!json_doc.isObject())
    {
        qDebug() << "doc is not a object";
        QMessageBox::warning(this,"提示","解析数据失败!", QMessageBox::Ok);
        return;
    }

    QJsonObject json_obj = json_doc.object();
    QStringList keys = json_obj.keys();

    for (int i = 0; i < json_obj.size(); i++)
    {
        if (keys[i] == "time")
        {
            QStringList split_list = json_obj.value(keys[i]).toString().split(" ");
            this->today_date = split_list.at(0);
            this->cur_time = split_list.at(1);
            qDebug() << "today_date: " << today_date;
            qDebug() << "cur_time: " << cur_time;
        }
        if (keys[i] == "cityInfo")
        {
            QJsonObject citylnfo_value = json_obj.value(keys[i]).toObject();
            QStringList citylnfo_value_keys = citylnfo_value.keys();
            for (int j = 0; j < citylnfo_value.size(); j++)
            {
                if (citylnfo_value_keys[j] == "city")
                {
                    this->cur_city = citylnfo_value.value(citylnfo_value_keys[j]).toString();
                    qDebug() << "cur_city: " << cur_city;
                }
                if (citylnfo_value_keys[j] == "updateTime")
                {
                    this->updata_time = citylnfo_value.value(citylnfo_value_keys[j]).toString();
                    qDebug() << "updateTime: " << updata_time;
                }
            }

        }

        if (keys[i] == "data")
        {
            QJsonObject data_value = json_obj.value(keys[i]).toObject();
            QStringList data_value_keys = data_value.keys();
            for (int k = 0; k < data_value.size(); k++)
            {
                if (data_value_keys[k] == "shidu")
                {
                    this->cur_him = data_value.value(data_value_keys[k]).toString();
                    qDebug() << "cur_him: " << cur_him;
                }
                if (data_value_keys[k] == "pm25")
                {
                    this->today_pm25 = data_value.value(data_value_keys[k]).toInt();
                    qDebug() << "today_pm25: " << today_pm25;
                }
                if (data_value_keys[k] == "pm10")
                {
                    this->today_pm10 = data_value.value(data_value_keys[k]).toInt();
                    qDebug() << "today_pm10: " << today_pm10;
                }
                if (data_value_keys[k] == "quality")
                {
                    this->today_air_quality = data_value.value(data_value_keys[k]).toString();
                    qDebug() << "today_air_quality: " << today_air_quality;
                }
                if (data_value_keys[k] == "wendu")
                {
                    this->cur_tem = data_value.value(data_value_keys[k]).toString() + QString("℃");
                    qDebug() << "cur_tem: " << cur_tem;
                }
                if (data_value_keys[k] == "forecast")
                {
                    QJsonValue forecast_value = data_value.value(data_value_keys[k]);
                    QJsonArray forecast_value_arr = forecast_value.toArray();
                    for (int h = 0; h < 7; h++) // 只读取七天有效数据
                    {
                        QJsonObject forecast_value_object = forecast_value_arr[h].toObject();
                        QStringList forecast_value_object_keys = forecast_value_object.keys();
                        for (int r = 0; r < forecast_value_object_keys.size(); r++)
                        {
                            if (forecast_value_object_keys[r] == "high")
                            {
                                this->tem_max_list.append(forecast_value_object.value(forecast_value_object_keys[r]).toString());
                                qDebug() << "tem_max_list" << h << tem_max_list.at(h);
                            }

                            if (forecast_value_object_keys[r] == "low")
                            {
                                this->tem_min_list.append(forecast_value_object.value(forecast_value_object_keys[r]).toString());
                                qDebug() << "tem_min_list" << h << tem_min_list.at(h);
                            }

                            if (forecast_value_object_keys[r] == "week")
                            {
                                this->week_list.append(forecast_value_object.value(forecast_value_object_keys[r]).toString());
                                qDebug() << "week_list " << h << week_list.at(h);
                            }

                            if (forecast_value_object_keys[r] == "sunrise" && h == 0)
                            {
                                this->sum_time_list.append(forecast_value_object.value(forecast_value_object_keys[r]).toString());
                                qDebug() << "sunrise: " << sum_time_list.at(0);
                            }

                            if (forecast_value_object_keys[r] == "sunset" && h == 0)
                            {
                                this->sum_time_list.append(forecast_value_object.value(forecast_value_object_keys[r]).toString());
                                qDebug() << "sunset: " << sum_time_list.at(1);
                            }

                            if (forecast_value_object_keys[r] == "fx" && h == 0)
                            {
                                this->today_wind = forecast_value_object.value(forecast_value_object_keys[r]).toString();
                                qDebug() << "today_wind: " << today_wind;
                            }

                            if (forecast_value_object_keys[r] == "type")
                            {
                                this->weather_list.append(forecast_value_object.value(forecast_value_object_keys[r]).toString());
                                qDebug() << "weather_list: " << h << weather_list.at(h);
                            }

                            if (forecast_value_object_keys[r] == "notice" && h == 0)
                            {
                                this->today_callWord = forecast_value_object.value(forecast_value_object_keys[r]).toString();
                                qDebug() << "today_callWord: " << today_callWord;
                            }
                        }
                    }
                }
            }
        }
    }

}

// 将JSON数据显示在QT界面上
void Widget_funcD_Weather::show_json()
{
    // 显示城市
    this->ui->textEdit->setText(this->cur_city);

    // 天气
    set_label_picture(weather_list.at(0), *this->ui->weather_label);
    set_label_text(weather_list.at(0), *this->ui->weather_text_label);

    // 空气质量
    set_label_picture("空气质量", *this->ui->air_quality_label);
    set_label_text(this->today_air_quality, *this->ui->air_quality_text);
    // pm10
    set_label_picture("pm10", *this->ui->pm10_label);
    set_label_text(QString::number(this->today_pm10), *this->ui->pm10_text);

    // pm25
    set_label_picture("pm25", *this->ui->pm25_label);
    set_label_text(QString::number(this->today_pm25), *this->ui->pm25_text);

    // 太阳上山
    set_label_picture("太阳升起", *this->ui->sun_rise_label);
    set_label_text(this->sum_time_list.at(0), *this->ui->sun_rise_text);

    // 太阳下山
    set_label_picture("太阳落山", *this->ui->sun_down_label);
    set_label_text(this->sum_time_list.at(1), *this->ui->sum_down_text);

    // 温度
    set_label_picture("温度", *this->ui->tem_label);
    set_label_text(this->cur_tem, *this->ui->tem_text);

    // 湿度
    set_label_picture("湿度", *this->ui->him_label);
    set_label_text(this->cur_him, *this->ui->him_text);

    // 日期
    set_label_text(this->today_date, *this->ui->data_label);

    // 星期
    set_label_text(this->week_list.at(0), *this->ui->week_tabel);

    // 时间
    set_label_picture("时间", *this->ui->time_label);
    set_label_text(this->cur_time, *this->ui->time_text);

    // 气温曲线
    int coldest_data[7];
    int hotest_data[7];
    for (int i = 0; i < 7; i++)
    {
        sscanf(this->tem_max_list.at(i).toUtf8().constData(), "高温 %d℃", &hotest_data[i]);
        sscanf(this->tem_min_list.at(i).toUtf8().constData(), "低温 %d℃", &coldest_data[i]);
    }
    this->ui->label->set_hotest_data(hotest_data);
    this->ui->label->set_coldest_data(coldest_data);
    this->ui->label->update(); // 重新触发绘画事件

    // 显示7天天气状况
    QLabel * week_arr[7] = {ui->week_1,ui->week_2,ui->week_3,ui->week_4,
                             ui->week_5,ui->week_6,ui->week_7};
    QLabel * week_weather_arr[7] = {ui->week_1_label,ui->week_2_label,ui->week_3_label,ui->week_4_label,
                             ui->week_5_label,ui->week_6_label,ui->week_7_label};
    QLabel * week_tem_max_arr[7] = {ui->week_1_hot,ui->week_2_hot,ui->week_3_hot,ui->week_4_hot,
                             ui->week_5_hot,ui->week_6_hot,ui->week_7_hot};
    QLabel * week_tem_min_arr[7] = {ui->week_1_cold,ui->week_2_cold,ui->week_3_cold,ui->week_4_cold,
                             ui->week_5_cold,ui->week_6_cold,ui->week_7_cold};
    for (int i = 0; i < 7; i++)
    {
        this->set_label_picture(this->week_list.at(i),*week_arr[i]);
        this->set_label_picture(this->weather_list.at(i),*week_weather_arr[i]);
        this->set_label_text(this->tem_max_list.at(i),*week_tem_max_arr[i]);
        this->set_label_text(this->tem_min_list.at(i),*week_tem_min_arr[i]);
    }
}

// 清除上一次搜索的JSON数据
void Widget_funcD_Weather::clear_json()
{
    this->tem_max_list.clear();
    this->tem_min_list.clear();
    this->weather_list.clear();
    this->week_list.clear();
    this->sum_time_list.clear();
}

// 接受到数据后，先json数据放入文件中pm10_label，再解析JSON数据，最后显示JSON数据
void Widget_funcD_Weather::onReplied(QNetworkReply *reply)
{
    // 获取相应码
    int status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

    if (reply->error() != QNetworkReply::NoError || status_code != 200)
    {
        QMessageBox::warning(this,"提示","请求数据失败!", QMessageBox::Ok);
    }
    else
    {
        QByteArray reply_data = reply->readAll();
        QByteArray byteArray = QString(reply_data).toUtf8();
        QFile file("./weather.json");
        file.open(QFile::WriteOnly);
        file.write(byteArray);
        file.close();
    }

    reply->deleteLater();
    this->clear_json(); // 清除上一次搜索的JSON数据
    this->anlalysis_joson(); // 解析对应城市的JSON数据
    this->show_json(); // 将数据显示
}

// 搜索城市按键
void Widget_funcD_Weather::on_pushButton_clicked()
{
    QString city_code;
    city_code = find_city(this->ui->lineEdit->text());
    if (city_code == NULL)
    {
        return;
    }
    QString city_url;
    city_url = "http://t.weather.itboy.net/api/weather/city/" + city_code; // 得到对应城市天气API入口

    this->city_url = city_url;

    this->get_joson(); // 获取对应城市的JSON数据
}
